/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* MpmProjectCirculatedService
* 项目传阅反馈
*
* 修改纪录
* 2021-07-14 版本：1.0 chengengwei 创建。
* @version 版本：1.0
* @author 作者：chengengwei
* 创建日期：2021-07-14
*/
package com.topscomm.mpm.service.impl;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.cbo.pojo.*;
import com.topscomm.cbo.service.ICboApprovalNodeInsService;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.MpmProjectCirculatedEntity;
import com.topscomm.mpm.pojo.MpmProjectCirculatedMemberEntity;
import com.topscomm.mpm.service.IMpmProjectCirculatedMemberService;
import com.topscomm.mpm.service.IMpmProjectCirculatedService;
import com.topscomm.mpm.service.impl.auto.MpmProjectCirculatedServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.common.TapSystemConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service(value = "mpmProjectCirculatedService")
@Scope(value = "singleton")
public class MpmProjectCirculatedService extends MpmProjectCirculatedServiceAuto implements IMpmProjectCirculatedService {

	@Autowired
	private ICboApprovalNodeInsService cboApprovalNodeInsService;

	@Autowired
	private IMpmProjectCirculatedMemberService mpmProjectCirculatedMemberService;

	@Autowired
	private ICboUserService cboUserService;

	@Autowired
	private ICboMessageSysService cboMessageSysService;

	@Autowired
	private ICboMessageAppService cboMessageAppService;

	/**
	 * @author: chengengwei
	 * @date: 2021-07-14
	 * @param entity
	 * @description:单号生成
	 * @modify:
	 */
	@Override
	protected void beforeInsert(BasicEntity entity){
		super.beforeInsert(entity);
		if (entity.getId() <= 0) {// 赋值Id和单号
			long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
			entity.setId(arrayId[0]);
			String docNo = String.valueOf(arrayId[0]);
			docNo = docNo.substring(0, 6) + docNo.substring(9);
			entity.setValue(MpmProjectCirculatedEntity.FieldDocno, docNo);
		}
	}

	/**
	 * @description: 保存退回传阅人code
	 * @author: chengengwei
	 * @date: 2021-07-14
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveReturnedcirculatedCode(Map<String, Object> paraMap) {
		String code = "," + ConvertUtil.convertToString(paraMap.get("code")) + ",";
		String id = ConvertUtil.convertToString(paraMap.get("id"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" update MpmProjectCirculated set {0} = '{1}' where id = {2} ",
				MpmProjectCirculatedEntity.FieldReturnedcirculatedcode, code, id);
		this.selectExecute(sql.toString());
	}

	/**
	 * @author: chengengwei
	 * @date: 2021-07-16
	 * @description:查询项目经理退回理由
	 * @modify:
	 */
	@Override
	public Map<String, Object> getManangerOpinion(Map<String, Object> paraMap) {
		String nodeinsid = ConvertUtil.convertToString(paraMap.get("nodeinsid"));
		StringBufferProxy whereSql = new StringBufferProxy();
		whereSql.appendSingle(" id = ( select {0} from {1} where id = {2} ) ",
				CboApprovalNodeInsEntity.FieldPrenodeinsid, CboApprovalNodeInsEntity.tableName, nodeinsid);
		List<CboApprovalNodeInsEntity> cboApprovalNodeInsEntities = this.cboApprovalNodeInsService
				.queryByWhere(whereSql.toString());
		Map<String, Object> resultMap = new HashMap<>();
		if (!cboApprovalNodeInsEntities.isEmpty()) {
			resultMap.put("manangerOpinion", cboApprovalNodeInsEntities.get(0).getApprovalopinion());
		}
		return resultMap;
	}

	/**
	 * @author: chengengwei
	 * @date: 2021-07-16
	 * @description:对项目成员发送消息
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void sendMessageToMember(String sourceid) {
		StringBufferProxy whereSql = new StringBufferProxy();
		whereSql.appendSingle(" {0} = {1} ", MpmProjectCirculatedMemberEntity.FieldSourceid, sourceid);
		List<MpmProjectCirculatedMemberEntity> mpmProjectCirculatedMemberEntities = this
				.mpmProjectCirculatedMemberService.queryByWhere(whereSql.toString());
		whereSql.clear();
		// 拼接所有项目成员
		if (!mpmProjectCirculatedMemberEntities.isEmpty()) {
			// 查询传阅反馈记录
			MpmProjectCirculatedEntity mpmProjectCirculatedEntity = this.queryById(sourceid);
			String tempCodes = mpmProjectCirculatedMemberEntities.stream().map(item -> item.getProjectmembercode())
					.collect(Collectors.joining(","));
			// 项目成员去重
			String[] tempCodesArr = tempCodes.split(",");
			String memberCodes = "'" + new ArrayList<>(Arrays.asList(tempCodesArr)).stream()
					.distinct().collect(Collectors.joining("','")) + "'";
			whereSql.appendSingle(" code in ({0}) ", memberCodes);
			// 查询所有项目成员信息
			List<CboUserEntity> cboUserEntities = this.cboUserService
					.queryByWhere(whereSql.toString());
			// 查询传阅人姓名工号
			List<BasicEntity> sysBatchList = new ArrayList<>();
			cboUserEntities.forEach(user -> {
				// 查找项目成员被谁传阅
				List<MpmProjectCirculatedMemberEntity> filterList = mpmProjectCirculatedMemberEntities
						.stream().filter(item -> {
					if (item.getProjectmembercode() != null) {
						return item.getProjectmembercode().contains("," + user.getCode() + ",");
					} else {
						return false;
					}
				}).collect(Collectors.toList());
				String content = String.format(MpmSystemConst.RemindProjectMemberMessage,
						filterList.get(0).getCirculatedname() + "【" + filterList.get(0).getCirculatedcode() + "】",
						mpmProjectCirculatedEntity.getProjectname());
				// 给项目成员发送App提醒
				Map<String, Object> appMap = new HashMap<>();
				appMap.put(CboMessageAppEntity.FieldSourceid, mpmProjectCirculatedEntity.getId());
				appMap.put(CboMessageAppEntity.FieldSourcetype, mpmProjectCirculatedEntity.tableName);
				appMap.put("state", 0);
				appMap.put(CboMessageAppEntity.FieldSendcount, 0);
				appMap.put("usercode", user.getCode());
				appMap.put(CboMessageAppEntity.FieldContent, content);
				appMap.put(CboMessageAppEntity.FieldExtendfield1, "项目任命提醒");
				this.cboMessageAppService.insertMap(appMap);
				// 给项目成员发送系统提醒
				CboMessageSysEntity sysEntity = new CboMessageSysEntity();
				sysEntity.setSourcetype(mpmProjectCirculatedEntity.tableName);
				sysEntity.setSourceid(mpmProjectCirculatedEntity.getId());
				sysEntity.setReceivercode(user.getCode());
				sysEntity.setReceivername(user.getName());
				sysEntity.setState(0);
				sysEntity.setSubject("项目任命提醒");
				sysEntity.setContent(content);
				sysBatchList.add(sysEntity);
			});
			this.cboMessageSysService.insertBatch(sysBatchList);
		}
	}

	/**
	 * @author: chengengwei
	 * @date: 2021-07-16
	 * @description:会签等待节点退回后将单据状态置为2
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	protected void afterApprove(TapEntity billEntity, CboApprovalNodeInsEntity nodeIns,
								CboApprovalNodeEntity node, SessionUserBean sessionUserBean) {
		MpmProjectCirculatedEntity mpmProjectCirculatedEntity = (MpmProjectCirculatedEntity) billEntity;
		String nodeid = ParameterCache.getValue(MpmSystemConst.SelectProjectMemberNodeId, "0");
		// 当前节点为选择项目成员节点
		if (nodeid.equals(ConvertUtil.convertToString(node.getId()))) {
			StringBufferProxy whereSql = new StringBufferProxy();
			// 查询当前单据节点为选择项目成员节点的节点实例审批日期为空的数量，若为0则全部审批。
			whereSql.appendSingle(" nodeid = {0} and sourcetype = '{1}' and sourceid = {2} and prenodeinsid = {3} " +
							"and approvaldate is null ", nodeid, mpmProjectCirculatedEntity.getTableName(),
					mpmProjectCirculatedEntity.getId(), nodeIns.getPrenodeinsid());
			int totalCount = this.cboApprovalNodeInsService.getCount(whereSql.toString());
			whereSql.clear();
			// 若全部审批，则查询是否有不同意的节点实例
			if (totalCount == 0) {
				whereSql.appendSingle(" nodeid = {0} and sourcetype = '{1}' and sourceid = {2} and state = '{3}'" +
								" and prenodeinsid = {4} ", nodeid, mpmProjectCirculatedEntity.getTableName(),
						mpmProjectCirculatedEntity.getId(), TapSystemConst.TapApprovalNodeStateEnum.UnApproved,
						nodeIns.getPrenodeinsid());
				int unapprovalCount = this.cboApprovalNodeInsService.getCount(whereSql.toString());
				whereSql.clear();
				if (unapprovalCount > 0) {
					mpmProjectCirculatedEntity.setState(TapSystemConst.TapApprovalFlowStateEnum.Back);
					this.updateEntity(mpmProjectCirculatedEntity);
				}
			}
		}
		super.afterApprove(billEntity, nodeIns, node, sessionUserBean);
	}

	/**
	 * @author: chengengwei
	 * @date: 2021-07-16
	 * @description:查询传阅反馈id
	 * @modify:
	 */
	@Override
	public Map<String, Object> queryCirculatedIdByProjectCode(Map<String, Object> paraMap) {
		String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
		StringBufferProxy whereSql = new StringBufferProxy();
		whereSql.appendSingle(" {0} = '{1}' ", MpmProjectCirculatedEntity.FieldProjectcode, projectcode);
		List<Map<String, Object>> maps = this.queryMapByWhere(whereSql.toString());
		if (maps.isEmpty()) {
			return new HashMap<>();
		} else {
			return maps.get(0);
		}
	}
}
